package profiles;

import global.Global;

import java.io.IOException;
import java.text.NumberFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import reports.DetailReport;
import server.Initialize;
import server.db.StmtHelper;
import server.json.FunctionalJSON;
import server.objects.Photo;
import server.objects.User;
import tables.SaveForm;
import tables.FormsTable;
import tables.LeadsTable;
import tables.UpdateForm;

import ajaxmethods.SessionMethod;

public class RealtorProfile extends SessionMethod {

	public void perform(HttpServletRequest request,HttpServletResponse response)
	{
		super.perform(request, response);
		if(global.isLoggedIn.f(request))
		{
			StringBuffer sb = new StringBuffer();
			Global global = new Global(request);
			User user = global.getUser();
			JSONArray listings;
			try {
				
				
				//TODO: Get the actual agents listings
				listings = FunctionalJSON.mapToJSONArray.f(StmtHelper.db("select zillowID,price,useCode,finishedSQFT,bathrooms,bedrooms, (select concat(street,' ',city,', ',state,' ',zip))  as ADDRESS,"+
						" ifnull((select image_url from photos where photos.zillowID=alllist.zillowID and photos.photo_num=1),'"+Photo.getNoPhotoURL()+"') IMGURL"+
				" from alllist group by useCode,finishedSQFT,bathrooms,bedrooms,street,city,state,zip,zillowID limit 20").collectIntoMaps.unsafeGet());
			sb.append("<div id=\"homeWorkspaceWrapper\"><div id=\"homeWorkspace\" class=\"realtorprofile\">");
			
			
			JSONObject agent = this.getAgent(user.id);
			
			sb.append("<div id=\"shortsection\" class=\"sidesection\"><h2 style=\"margin:0px;\" class=\"fullname\">"+agent.get("fullname")+"</h4>");
			sb.append("<div id=\"photo\"><img class=\"listViewImage\" src=\""+Initialize.appURL()+"/"+agent.get("image_url")+"\"></div>");
			sb.append("<div class=\"agentfields\">");
			sb.append("<div>"+agent.get("officename")+" - "+agent.get("officeaddress")+"</div><div>"+agent.get("officephone")+"</div></div></div>");
			
			sb.append("<div class=\"relative paddingtwofour\"><div class=\"viewtabs\"><div class=\"tab selected\">");
			sb.append("<a class=\"mylistings\" onclick=\"toggleListView(this)\">My Listings</a></div>");
			sb.append("<div class=\"tab\">");
			sb.append("<a class=\"marketing\" onclick=\"toggleListView(this)\">Lead Capture Tools</a></div>");
			sb.append("<div class=\"tab\">");
			sb.append("<a class=\"contacts\" onclick=\"toggleListView(this)\">My Contacts</a></div>");
			sb.append("</div></div>");
			
			
			sb.append("<div class=\"scrollable\">");
		
			sb.append("<div id=\"leadtools\" style=\"display:none;position:relative;height: 100%;\">");
			
			sb.append("<div id=\"head\"><div style=\"float:left;margin:20px;\"><a style=\"padding:8px;\" class=\"esobutton\" onclick=\"toggleTable($('#pagerlink'),0);\">How It Works</a></div><div class=\"headerlinksWrapper\"><div class=\"headerlinks\"><a class=\"esobutton\" id=\"myformslink\" onclick=\"toggleTable(this);\">My Forms</a><a id=\"pagerlink\" class=\"esobutton\" onclick=\"toggleTable(this,1);\">New Form</a><a class=\"esobutton\" id=\"myleadslink\" onclick=\"toggleTable(this);\">My Leads</a></div></div>");
			sb.append("<div style=\"position:relative;width:160px;float:right;margin:14px;\" id=\"action\"><a style=\"float:left;\" class=\"prev disabled esobutton\" >&#x25B2;</a>" +
			"<span id=\"noobjectsfound\">No Forms</span><span id=\"displaynumobjects\" style=\"width:120px;position:absolute;padding:0px 1px;\"><span id=\"start\">1</span>&nbsp;to&nbsp;<span id=\"end\">7</span>&nbsp;of&nbsp;<span id=\"total\">&nbsp;&nbsp;</span></span>" +
			"<a style=\"float:right;\" class=\"next esobutton\" >&#x25BC;</a></div></div>");
			
			sb.append("<div id=\"myforms\" class=\"page\" style=\"display:none;position:relative;height: 97%;\">");
			sb.append("<div class=\"\"><div id=\"noscrollsidepanel\"><p style=\"margin-left:15px;width:140px;position:absolute;font-size:11px;\" class=\"tipStyle\">Hover over a form in the table to see what it will look like on your website.</p>" +
					"<div class=\"formsmall\"></div></div>");
			sb.append("<div id=\"scrollForms\"></div></div></div>");
	
			sb.append("<div id=\"myleads\" class=\"page\" style=\"display:none;position:relative;height: 97%;\">");
			sb.append("<div class=\"\"><div id=\"noscrollsidepanel\"><p style=\"width:170px;position:absolute;\" class=\"tipStyle\">Hover over a lead in the table for more info.</p>" +
					"<div class=\"leadsmall\"></div></div>");
			sb.append("<div id=\"scrollLeads\"></div></div></div>");
			
			
			sb.append("<div id=\"pager\" class=\"page\">");
			sb.append("<div class=\"pageitems\"><div class=\"pageitem\">");
			sb.append("<h2>Lead Generation For Your Website And Facebook Page</h2>");
			sb.append("<div id=\"detailview\" style=\"display:block;width:140px;\"><a class=\"lastAction\"></a><a class=\"nextAction\">Get Started &#x25BA;</a></div>");
			
			sb.append("<div id=\"sidepane\">" +
					"<p>Create your personal contact submission form and integrate with emails, social media, and your website.</p>" +
					"<p>The <a>My Leads</a> button above allows you to manage all your leads that submit your forms that we generate for you.</p><p>The <a>My Forms</a> button allows you to manage your forms.  If you're curious about how you're forms are performing we provide conversion statistics for each form you generate along with tips on how you can improve conversion.</p>" +
					"</div>");
			String formTitle = "Contact "+agent.get("fullname");
			sb.append("<div id=\"leadform0\" >");
			sb.append("<div id=\"theme\"><div class=\"floatInputWrapper\" ><h2 class=\"formtitle\">"+formTitle+"</h2>" +
					"<div id=\"fullname\">" +
					"<p class=\"textbox halfleft\">"+
				    "<label for=\"firstname\">First Name</label>"+
				    "<input type=\"text\" id=\"firstname\" class=\"esoinput\" name=\"firstname\" value=\"\" title=\"firstname\" tabindex=\"1\">"+
				    "</p><p class=\"textbox halfright\">"+
				    "<label for=\"lastname\">Last Name</label>"+
				    "<input type=\"text\" id=\"lastname\" class=\"esoinput\" name=\"lastname\" value=\"\" title=\"lastname\" tabindex=\"2\">"+
				    "</p><div class=\"errorText\">&nbsp;</div></div>" +
				    "<div id=\"email\"><p class=\"textbox\">"+
				    "<label for=\"email\">Email</label>"+
				    "<input type=\"text\" class=\"esoinput\" name=\"email\" value=\"\" title=\"username\" tabindex=\"3\">"+
				    "</p><div class=\"errorText\">&nbsp;</div></div>"+
				    "<div id=\"home\" style=\"display:none;\">" +
				    "<p class=\"textbox phonebox\">" +
				    "<label for=\"home\">Home Phone</label>"+
				    "("+
				    "<input type=\"text\" id=\"areacode\" maxlength=\"3\" class=\"esoinput\" name=\"areacodehome\" value=\"\" tabindex=\"4\">"+
				    ")"+
				    "<input type=\"text\" id=\"threedigit\" maxlength=\"3\" class=\"esoinput\" name=\"threedigithome\" value=\"\" tabindex=\"5\">"+
				    "-" +
				    "<input type=\"text\" id=\"fourdigit\" maxlength=\"4\"  class=\"esoinput fourdigit\" name=\"fourdigithome\" value=\"\" tabindex=\"6\">"+
				    "</p><div class=\"errorText\">&nbsp;</div></div>" +
				    "<div id=\"cell\" style=\"display:none;\">" +
				    "<p class=\"textbox phonebox\">" +
				    "<label for=\"home\">Cell Phone</label>"+
				    "("+
				    "<input type=\"text\" id=\"areacode\" maxlength=\"3\" class=\"esoinput\" name=\"areacodecell\" value=\"\" tabindex=\"7\">"+
				    ")"+
				    "<input type=\"text\" id=\"threedigit\" maxlength=\"3\" class=\"esoinput\" name=\"threedigitcell\" value=\"\" tabindex=\"8\">"+
				    "-" +
				    "<input type=\"text\" id=\"fourdigit\" maxlength=\"4\" class=\"esoinput fourdigit\" name=\"fourdigitcell\" value=\"\" tabindex=\"9\">"+
				    "</p><div class=\"errorText\">&nbsp;</div></div>" +
				    "<div id=\"message\"><p class=\"textbox\">"+
				    "<label for=\"message\">Leave Me A Message</label>"+
				    "<textarea type=\"text\" class=\"esoinput\" name=\"message\" value=\"\" title=\"message\"></textarea>" +
				    "</p><div class=\"errorText\">&nbsp;</div></div>" +
				    "</div><button class=\"esobutton\" id=\"submitlead\" onclick=\"submitLead();return false;\" title=\"send\" type=\"submit\">Send</button>");
			sb.append("</div></div>");
			sb.append("</div>");
			sb.append("<div class=\"pageitem\">");
			sb.append("<ul class=\"progressmap-steps\"><li class=\"inline-block progressmap-step progressmap-step-selected\">" +
					"<div class=\"progressmapdiv\"><span class=\"progressmap-border-start\"></span><span class=\" inline-block progressmap-checked\" style=\"display: none; zoom: normal; \"></span><span class=\"progressmap-text\">Step 1: Choose Your Title & Form Fields</span></div>" +
					"</li><li class=\"inline-block progressmap-step\">" +
					"<div class=\"progressmapdiv\"><span class=\"inline-block progressmap-checked\" style=\"display: none; \"></span><span class=\"progressmap-text\">Step 2: Choose Your Theme</span></div>" +
					"</li><li class=\"inline-block progressmap-step\">" +
					"<div class=\"progressmapdiv\"><span class=\"inline-block progressmap-checked\" style=\"display: none; \"></span><span class=\"progressmap-text\">Step 3: Save Form & Generate Code</span></div>" +
					"</li></ul>");
			//sb.append("<h2>Step 1: Choose Your Title & Form Fields</h2>");
			sb.append("<div id=\"detailview\" style=\"margin-right:400px;\"><a class=\"lastAction\">&#x25C0; Go Back</a></div><div id=\"detailview\"><a class=\"nextAction\">Step 2 &#x25BA;</a></div>");
			sb.append("<div id=\"choosefields\"><div id=\"sidepane\">" +
					"<div id=\"formname\">"+
				    "<label for=\"formname\"><h3>Form Title</h3></label>"+
				    "<input type=\"text\" class=\"esoinput\" name=\"title\" value=\""+formTitle+"\" title=\"form title\" tabindex=\"1\">"+
				    "<div class=\"errorText\">&nbsp;</div></div>");
			sb.append("<div id=\"addremovefields\"><p class=\"checkbox\">" +
					"<label for=\"addfields\"><h3>Form Fields</h3></label>" +
					"<div><input type=\"checkbox\" class=\"esoinput\" checked=\"true\" name=\"fullname\">" +
					"<a onclick=\"javascript:$(this).prev().click();\">First And Last Name</a></div>" +
					"<div><input type=\"checkbox\" class=\"esoinput\" checked=\"true\" name=\"email\">" +
					"<a onclick=\"javascript:$(this).prev().click();\">Email</a></div>" +
					"<div><input type=\"checkbox\" class=\"esoinput\" name=\"home\">" +
					"<a onclick=\"javascript:$(this).prev().click();\">Home Phone</a></div>" +
					"<div><input type=\"checkbox\" class=\"esoinput\" name=\"cell\">" +
					"<a onclick=\"javascript:$(this).prev().click();\">Cell Phone</a></div>" +
					"<div><input type=\"checkbox\" class=\"esoinput\" checked=\"true\" name=\"message\">" +
					"<a onclick=\"javascript:$(this).prev().click();\">Leave A Message</a></div>" +
					"</p></div>");
			sb.append("</div></div>");		
			sb.append("<div id=\"leadform1\"></div>");
			sb.append("</div>");
			sb.append("<div class=\"pageitem\">");
			sb.append("<ul class=\"progressmap-steps\"><li class=\"inline-block progressmap-step progressmap-step-2\">" +
					"<div class=\"progressmapdiv\"><span class=\" inline-block progressmap-checked\" style=\"display: none; zoom: normal; \"></span><span class=\"progressmap-text\">Step 1: Choose Your Title & Form Fields</span></div>" +
					"</li><li class=\"inline-block progressmap-step progressmap-step-selected\">" +
					"<div class=\"progressmapdiv\"><span class=\"progressmap-border-start\"></span><span class=\"inline-block progressmap-checked\" style=\"display: none; \"></span><span class=\"progressmap-text\">Step 2: Choose Your Theme</span></div>" +
					"</li><li class=\"inline-block progressmap-step\">" +
					"<div class=\"progressmapdiv\"><span class=\"inline-block progressmap-checked\" style=\"display: none; \"></span><span class=\"progressmap-text\">Step 3: Save Form & Generate Code</span></div>" +
					"</li></ul>");
			//sb.append("<h2>Step 2: Choose Your Theme</h2>");
			sb.append("<div id=\"detailview\" style=\"margin-right:400px;\"><a class=\"lastAction\">&#x25C0; Go Back</a></div><div id=\"detailview\"><a class=\"nextAction\">Step 3 &#x25BA;</a></div>");
			sb.append("<div id=\"choosefields\"><div id=\"sidepane\">");
			sb.append("<div id=\"choosetheme\"><p class=\"checkbox\">" +
					"<label for=\"addfields\"></p><h3>Themes</h3></label>" +
					"<div><input type=\"radio\" onclick=\"javascript:updateTheme(this);\" id=\"default\" class=\"esoinput\" checked name=\"theme\">" +
					"<a onclick=\"javascript:$(this).prev().click();\">Default</a></div>" +
					"<div><input type=\"radio\" onclick=\"javascript:updateTheme(this);\" id=\"oldschool\" class=\"esoinput\" name=\"theme\">" +
					"<a onclick=\"javascript:$(this).prev().click();\">Simple</a></div>" +
					"<div><input type=\"radio\" onclick=\"javascript:updateTheme(this);\" id=\"light\" class=\"esoinput\" name=\"theme\">" +
					"<a onclick=\"javascript:$(this).prev().click();\">Light</a></div>" +
					"<div><input type=\"radio\" onclick=\"javascript:updateTheme(this);\" id=\"dark\" class=\"esoinput\" name=\"theme\">" +
					"<a onclick=\"javascript:$(this).prev().click();\">Dark</a></div>" +
					"<div><input type=\"radio\" onclick=\"javascript:updateTheme(this);\" id=\"newage\" class=\"esoinput\" name=\"theme\">" +
					"<a onclick=\"javascript:$(this).prev().click();\">Shadow</a></div>" +
					"</div>");
			sb.append("<div id=\"colors\"><div id=\"txtcolor\"><h5>Text Color</h5><input style=\"width:40px;font-size:10px;height:30px;border-radius:2em;color:transparent;\" id=\"textcolor\" name=\"textcolor\" type=\"text\" onchange=\"updateColor(this);\" value=\"transparent\" class=\"iColorPicker\" /></div>");
			sb.append("<div id=\"bckgrndcolor\"><h5>Background Color</h5><input style=\"width:40px;font-size:10px;height:30px;border-radius:2em;color:transparent;\" id=\"backgroundcolor\" name=\"backgroundcolor\" type=\"text\" onchange=\"updateColor(this);\" value=\"transparent\" class=\"iColorPicker\" /></div>" +
					"</div>");
	
			sb.append("</div></div>");		
			sb.append("<div id=\"leadform2\">");
			sb.append("</div></div>");
			
			sb.append("<div class=\"pageitem\">");
			sb.append("<ul class=\"progressmap-steps\"><li class=\"inline-block progressmap-step\">" +
					"<div class=\"progressmapdiv\"><span class=\" inline-block progressmap-checked\" style=\"display: none; zoom: normal; \"></span><span class=\"progressmap-text\">Step 1: Choose Your Title & Form Fields</span></div>" +
					"</li><li class=\"inline-block progressmap-step progressmap-step-2\">" +
					"<div class=\"progressmapdiv\"><span class=\"progressmap-border-start\"></span><span class=\"inline-block progressmap-checked\" style=\"display: none; \"></span><span class=\"progressmap-text\">Step 2: Choose Your Theme</span></div>" +
					"</li><li class=\"inline-block progressmap-step progressmap-step-selected\">" +
					"<div class=\"progressmapdiv\"><span class=\"inline-block progressmap-checked\" style=\"display: none; \"></span><span class=\"progressmap-text\">Step 3: Save Form & Generate Code</span></div>" +
					"</li></ul>");
			//sb.append("<h2>Step 3: Save Form</h2>");
			sb.append("<div id=\"detailview\" style=\"display:block;width:140px;\"><a class=\"lastAction\">&#x25C0; Go Back</a></div>");
			sb.append("<div id=\"choosefields\"><div id=\"sidepane\" style=\"margin: 20px 0px 0px 40px;\">");
			sb.append("<div id=\"saveform\">" +
					"<button onclick=\"javascript:saveGenerateForm();\" id=\"saveFormButton\" class=\"esobutton fatbutton\">Save Form And Generate Code</button>" +
					"<div id=\"code\" style=\"display:none;\"><p>Your New Form has been saved.</p><textarea id=\"codeembed\" style=\"width:284px;height: 60px;\"></textarea><p>Copy the code above to add it to your website or social media site.</p>" +
					"<textarea id=\"linkembed\" style=\"width:284px;height:30px;\"></textarea><p>Copy the link above to embed in Facebook.  Click <a target=\"_new\" href=\"http://www.techipedia.com/2009/create-facebook-page\">here</a> to learn more about adding this form to your Facebook page</p>" +
					"<div id=\"detailview\"><a onclick=\"toggleTable('#myformslink');\" class=\"detailLink\">View My Forms</a></div></div>" +
					"</div>");
			sb.append("</div></div>");		
			sb.append("<div id=\"leadform3\">");
			sb.append("</div></div>");
			sb.append("</div>");
			
			sb.append("<div id=\"leadlinks\" style=\"margin: 5px;position:absolute;bottom:0px;right:0px;\">" +
					"<a class=\"\">My Leads</a><span style=\"padding:0px 10px;\">|</span><a onclick=\"showMyTable('myleads','myforms');\" >My Forms</a>" +
					"</div>");
			
			sb.append("</div></div>");
			
			sb.append("<div id=\"mylistings\"><div id=\"head\">");
			sb.append("<div class=\"action\"><div class=\"insideAction insideActionLeft\"><a class=\"prev esobutton\" >&#x25C0; Prev</a><a class=\"next esobutton\">Next &#x25BA;</a></div>" +
			"<div class=\"insideAction insideActionRight\"><a class=\"mylistingsGen esobutton\">Add My Listings to Facebook</a></div></div></div>");
			sb.append("</div><div class=\"items\">");
			for(int i = 0; i < listings.length(); i ++)
			{
				JSONObject listing = ((JSONObject)listings.get(i));
				String typ = (String)listing.get("useCode");
				String address =  (String)listing.get("ADDRESS");
				String beds = (String)listing.get("bedrooms");
				String sqft =(String)listing.get("finishedSQFT");
				String primaryphoto = (String)listing.get("IMGURL");
				String bathrooms =(String)listing.get("bathrooms");
				String zillowID = (String)listing.get("zillowID");
				
				String price = NumberFormat.getCurrencyInstance().format(Integer.parseInt((String)listing.get("price")));
				sb.append("<div class=\"mediumReport\">");
				sb.append("<div class=\"content\" style=\"position: relative;margin-left:6px;width: 886px;height: 380px;\"><div id=\"photo\"><div class=\"medphotosize\">" +
						"<a id=\""+zillowID+"\" class=\"fancyphotoLink\" title=\""+address+"\"><img style=\"height: 300px;margin-top: 10px;\" src=\""+primaryphoto+"\"></a></div></div>");
				
				sb.append("<div id=\"propertyBrief\">");
				//TODO:Add Price Field
				sb.append("");
				sb.append("<h3 class=\"propaddress\">"+address+"</h3>");
				sb.append("<div class=\"price\"><span class=\"label\">Price:</span>"+price+"</div>");
				sb.append("<div class=\"beds\"><span class=\"label\">Bedrooms:</span>"+beds+"</div>");
				sb.append("<div class=\"baths\"><span class=\"label\">Bathrooms:</span>"+bathrooms+"</div>");
				sb.append("<div class=\"proptype\"><span class=\"label\">Property Type:</span>"+typ+"</div>");
				sb.append("<div class=\"sqft\"><span class=\"label\">Square Feet:</span>"+sqft+"</div>");
				sb.append("<div class=\"linkWrapper\"><div id=\"detailview\" ><a id=\""+zillowID+"\" title=\""+address+"\" class=\"detailLink moredetails\">More Details</a></div></div>");
				sb.append("</div>");
				sb.append("</div></div>");
			}
			sb.append("</div></div>");
			
			sb.append(javaScriptOut());
				
			data.put("HOME", sb.toString()).write(response.getWriter());
	
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} else
			try {
				data.put("signedout",true).write(response.getWriter());
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	public static JSONObject getAgent(Integer userid) {
		try {
			return FunctionalJSON.mapToJSONObject.f(StmtHelper.db("select idagents,image_url,fullname,contextpath,agentid,directline,officephone,mobile,fax,officename,officeaddress,emailaddress from agents where iduser=").addVariable(userid)
				.collectIntoMaps.unsafeGet());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public StringBuffer javaScriptOut() {
		StringBuffer sb = new StringBuffer();
		sb.append("<script src=\""+Initialize.appURL()+"/js/iColorPicker.js\" type=\"text/javascript\"></script>");
		sb.append("<script>");
		sb.append("$('.fancyphotoLink').click(function(){var link = $(this); if(link.find('img').attr('src').indexOf('nophotoavail')==-1)$.post('"+Initialize.appURL()+"/ajaxCall.jsp?do=reports.Photos',{zillowID:link.attr('id')},function(data, textStatus, XMLHttpRequest) {"+
		"	if(data){$.fancybox(data,{title:link.attr('title'),type:'image', transitionIn:'elastic',transitionOut:'elastic',easingIn:'easeOutBack',easingOut:'easeInBack',width:500});}});}); ");
		sb.append("function toggleListView(elem) {\n" +
				"if(!$(elem).parent().hasClass('selected'))\n" +
				"{"+
				"	$('.viewtabs .tab a').each(function(){if($(elem).attr('class')==$(this).attr('class')) $(this).parent().addClass('selected'); else $(this).parent().removeClass('selected'); });\n" +
				"if($(elem).hasClass('marketing')) {" +
				"	$('#homeWorkspace .action').fadeOut(function(){" +
				"		$('#homeWorkspace .scrollable > #mylistings').fadeOut(function(){" +
				"			toggleTable('#myformslink');" +
				"			$('#leadtools').fadeIn().parent().animate({height:600});" +
				"		});" +
				"});" +
				"}" +
				"else if($(elem).hasClass('mylistings'))" +
				"	$('#leadtools').fadeOut(function(){$('#homeWorkspace .action,.scrollable #mylistings').fadeIn();}).parent().animate({height:400});" +
				"}" +
				"}");
		sb.append("function showCreateForm(startersPistol) {console.log(startersPistol);\n" +
				"var pager = $('#pager').show().data('scrollable');" +
				"pager.seekTo(startersPistol);" +
				"$('#myforms,#myleads').fadeOut(function(){$('#head #action').hide(); });" +
				"}");
		sb.append("function showMyFormsTable(formtableid,data) {" +
				"	$.post('"+FormsTable.url()+"',data,function(result){" +
				"if(Login.check(result)) {" +
				"if(!result.hasAForm) {" +
				"	alert('You have no new forms at this time.');" +
				"	toggleSelected($('#leadtools .page').not(':hidden').attr('id')+'link');" +
				"}" +
				"else {" +
				"	showMyTable(formtableid,'myforms');" +
				"	$('#scrollForms').html(result.hasForm);" +
				"}" +
				"}});" +
				"}");
		sb.append("function showMyLeadsTable(leadtableid,formid) {\n" +
				"	var data={};" +
				"	if(formid)" +
				"		data.formid=formid;" +
				"	$.post('"+LeadsTable.url()+"',data,function(result){" +
						"if(Login.check(result)) {" +
						"if(!result.hasALead) {" +
						"	alert('You have no new leads at this time.');" +
						"	toggleSelected($('#leadtools .page').not(':hidden').attr('id')+'link');" +
						"}" +
						"else {" +
						"	showMyTable(leadtableid,'myforms');" +
						"	$('#scrollLeads').html(result.hasLead);" +
						"}" +
						"}});" +
				"		" +
				"" +
				"}");
		
		sb.append("function toggleSelected(linkid) {" +
				"	$('#'+linkid).addClass('selected').siblings().removeClass('selected');" +
				"}");
		sb.append("function showMyTable(tabletype,hidetable) {\n" +
				"	$('#head #action').show();" +
				"	$('#pager,#'+hidetable).fadeOut(function(){$('#'+tabletype).fadeIn();});" +
				"	$('#saveFormButton').show();" +
				"	$('#saveform #code').hide().find('textarea').each(function(){$(this).text('');});$('#leadform3').prev().prev().css('visibility','visible');" +
				"	$('#pager').data('scrollable').seekTo(1);" +
				"}");
		sb.append("function toggleTable(elem,startersPistol,data) {" +
				"	var elem = $(elem);" +
				"	if(!elem.hasClass('selected')) {" +
				"		elem.siblings().each(function(){$(this).removeClass('selected');});" +
				"		elem.addClass('selected');" +
						"if(elem.attr('id')=='myformslink')" +
						"	showMyFormsTable('myforms',data);" +
						"else if(elem.attr('id')=='myleadslink')" +
						"	showMyLeadsTable('myleads');" +
						"else if(elem.attr('id')=='pagerlink')" +
						"	showCreateForm(startersPistol);" +
				"	}" +
				"	else if(elem.attr('id')=='pagerlink')" +
				"		showCreateForm(startersPistol);" +
				"}");
		sb.append(DetailReport.javaScriptOut());
		sb.append("$(document).ready(function(){var previndex; $('#pager').scrollable({prev:'.lastAction',next:'.nextAction',touch:false,items:'.pageitems'," +
				"onBeforeSeek:function(){previndex = this.getIndex();}," +
				"onSeek:function(){console.log(this.getIndex());console.log(previndex);" +
				"$('#leadform'+this.getIndex()).html($('#leadform'+previndex).children());" +
				"}});" +
				"$('input[name=\"title\"]').keyup(function(){$('.formtitle').html($(this).val());});" +
				"$('input[type=\"checkbox\"]').click(function(){$('div#'+$(this).attr('name')).slideToggle();});});" +
				"function updateTheme(elem) {\n" +
				" $('#leadform2 #theme').attr('class',elem.id);\n" +
				"}" +
				"function updateColor(elem) {console.log(elem);" +
				" if(elem.attr('id')=='textcolor') {" +
				"	$('style#themestyles').html($('style#themestyles').html().replace(/#theme label,#theme h2,#theme button{color:.+}/gi,'#theme label,#theme h2,#theme button{color:'+elem.val()+'}'));" +
				"}" +
				" else if(elem.attr('id')=='backgroundcolor') {" +
				"	$('style#themestyles').html($('style#themestyles').html().replace(/#theme{background-color:.+}/gi,'#theme{background-color:'+elem.val()+'}'));" +
				"}" +
				"}" +
				"function saveGenerateForm() {\n " +
				"	$.post('"+SaveForm.url()+"',{formtitle:$('.formtitle').html(),content:$('#leadform3').html()+'<style>'+$('style#themestyles').html()+'</style>'}," +
						"function(data, textStatus, XMLHttpRequest) {" +
						"if(Login.check(data)) {" +
						"var scrollAPI = $('#scrollForms .verticalscroll').data('scrollable').addItem(data.addrow);" +
						"$('#saveFormButton').slideUp(function() {$('#saveform #code').slideDown(function(){$(this).find('textarea#codeembed').text(data.content);$(this).find('textarea#linkembed').text(data.link);$('#leadform3').prev().prev().css('visibility','hidden');" +
						"}); " +
					"});" +
				"}});"+
				"}");
		sb.append("</script>\n");
		sb.append("\n<style id=\"themestyles\">\n");
		sb.append("#theme {width: 350px;padding:0px 0px 8px 8px;}\n" +
				".floatInputWrapper {width: 230px;margin: 0px 5px;}\n" +
				"div#fullname {height: 60px;}\n" +
				"p.phonebox .esoinput {width: 36px;display: inline;}\n" +
				"p.phonebox .esoinput.fourdigit {width: 42px;}" +
				"p.phonebox label {display: block;}\n" +
				"#theme.oldschool,#theme.oldschool input,#theme.oldschool textarea  {border:1px solid #BBB;}\n" +
				"#theme.light,#theme.light input,#theme.light textarea {border:1px solid silver;box-shadow:1px 1px 2px silver;-webkit-box-shadow:1px 1px 2px silver;-moz-box-shadow:1px 1px 2px silver;}\n" +
				"#theme.dark,#theme.dark input,#theme.dark textarea {border:1px solid black;box-shadow:1px 1px 2px black;-webkit-box-shadow:1px 1px 2px black;-moz-box-shadow:1px 1px 2px black;}\n" +
				"#theme.newage {border:1px solid #EEE;border-radius:2em;-moz-border-radius:2em;-webkit-border-radius:1em;}\n" +
				"#theme.newage input,#theme.newage textarea {box-shadow: 0px 4px 10px #8B8B8B;-webkit-box-shadow: 0px 4px 10px #8B8B8B;-moz-box-shadow: 0px 4px 10px #8B8B8B;}\n" +
				"#theme.newage{-webkit-box-shadow: 0 4px 10px #8B8B8B;-moz-box-shadow: 0 4px 10px #8B8B8B;box-shadow: 0 4px 10px #8B8B8B;}\n" +
				"#theme.oldschool input,#theme.oldschool textarea,#theme.oldschool button{border-radius:0px;}" +
				".textbox.halfleft .esoinput, .textbox.halfright .esoinput {width: 94px;}\n" +
				".textbox .esoinput {padding: 5px;background: white;display: block;width: 218px;border: 1px solid #DDD;-webkit-border-radius: 4px;-moz-border-radius: 4px;border-radius: 4px;}\n" +
				"span.label, p.textbox label, p.remember label {color: #5C98DA;font-weight: bold;padding-right: 3px;}\n" +
				".textbox.halfleft {float: left;}\n" +
				".textbox.halfright {float: right;}\n" +
				".textbox {margin: 1px 0px;}\n" +
				"#theme button {padding: 5px 80px;margin:5px;}\n" +
				"#theme textarea {width: 310px;height: 80px;}\n" +
				"#theme .errorText {font-size: 13px;color: red;height: 10px;}\n" +
				"h2.formtitle {color: #5C98DA;margin: 7px;width:340px;}\n" +
				"#theme label,#theme h2,#theme button{color:na}\n" +
				"#theme{background-color:na}\n");
		sb.append("</style>\n");
		return sb;
	}
	
}
